package barney.davis.hume.it3048todo;

import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import barney.davis.hume.it3048todo.constants.TaskRepeat;
import barney.davis.hume.it3048todo.constants.TaskStatus;
import barney.davis.hume.it3048todo.dto.Task;
import barney.davis.hume.it3048todo.service.ITaskService;
import barney.davis.hume.it3048todo.service.TaskService;

/**
 * @author Tony
 *
 */
public class AddTaskActivity extends Activity {
	
	public static final String TASK_ID = "TASK_ID";
	private LocationListener locationListener;
	private LocationManager locationManager;
	private String output = "";
	private ITaskService taskService = new TaskService(this);
	private double lat;
	private double lon;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_task);
            
            locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
            
            locationListener  = new LocationListener() {

                @Override
                public void onLocationChanged(Location loc) {
                        // update our lat and lng values.
                    if(loc != null)
                    {
                    	output = Double.toString(loc.getLongitude()) + ", " + Double.toString(loc.getLatitude());
                    }
                        
                }

                @Override
                public void onProviderDisabled(String arg0) {
                        // TODO Auto-generated method stub
                        
                }

                @Override
                public void onProviderEnabled(String arg0) {
                        // TODO Auto-generated method stub
                        
                }

                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                        // TODO Auto-generated method stub
                        
                }
                
            };
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
            
            Spinner repeatSpinner = (Spinner) findViewById(R.id.spinner1);
            ArrayAdapter<CharSequence> repeatAdapter = ArrayAdapter.createFromResource(this, R.array.repeatValues, android.R.layout.simple_spinner_item);
            repeatAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            repeatSpinner.setAdapter(repeatAdapter);
            
            Spinner statusSpinner = (Spinner) findViewById(R.id.Spinner01);
            ArrayAdapter<CharSequence> statusAdapter = ArrayAdapter.createFromResource(this, R.array.statusValues, android.R.layout.simple_spinner_item);
            statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            statusSpinner.setAdapter(statusAdapter);
            
            Spinner complexSpinner = (Spinner) findViewById(R.id.complexSpinner);
            ArrayAdapter<CharSequence> complexAdapter = ArrayAdapter.createFromResource(this, R.array.complexValues, android.R.layout.simple_spinner_item);
            statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            complexSpinner.setAdapter(complexAdapter);
            
            TextView locationTextView = (TextView) findViewById(R.id.txtViewLocationData);
			locationTextView.setText("0.0, 0.0");
            
            Intent intent = getIntent();
            String id = intent.getStringExtra(TASK_ID);
            ITaskService taskService = new TaskService(this);
            if (id != null) {
            	//Populate fields with selectedTask info
				Task selectedTask;
				try {
					selectedTask = taskService.getTaskById(id);
					
					EditText TaskNameEdit = (EditText)findViewById(R.id.editText1);
					TaskNameEdit.setText(selectedTask.text);
					
					DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker1);
					datePicker.updateDate(selectedTask.dueDate.get(Calendar.YEAR), selectedTask.dueDate.get(Calendar.MONTH), selectedTask.dueDate.get(Calendar.DATE));
					
					TaskRepeat selectedRepeat = selectedTask.repeat;
					switch (selectedRepeat){
						case NONE:
							repeatSpinner.setSelection(0);
							break;
						case DAILY:
							repeatSpinner.setSelection(1);
							break;
						case WEEKLY:
							repeatSpinner.setSelection(2);
							break;
						case WEEKDAYS:
							repeatSpinner.setSelection(3);
							break;
						case WEEKENDS:
							repeatSpinner.setSelection(4);
							break;
						case MONTHY:
							repeatSpinner.setSelection(5);
							break;
						case YEARLY:
							repeatSpinner.setSelection(6);
							break;
						default:
							repeatSpinner.setSelection(0);
							break;
					}
					
					TaskStatus selectedStatus = selectedTask.status;
					switch (selectedStatus){
						case INPROGRESS:
							statusSpinner.setSelection(0);
							break;
						case OVERDUE:
							statusSpinner.setSelection(1);
							break;
						case COMPLETE:
							statusSpinner.setSelection(2);
							break;
						default:
							statusSpinner.setSelection(0);
							break;
					}
										
					double selectedComplex = selectedTask.complexity;
					boolean pointFive = false;
					if(selectedComplex == 0.5)
					{
						pointFive = true;
					}
					switch ((int)selectedComplex){
						case -1:
							complexSpinner.setSelection(0);
							break;
						case 0:
							if(!pointFive)
							{
								complexSpinner.setSelection(1);
							}
							else
							{
								complexSpinner.setSelection(2);
							}
							break;
						case 1:
							complexSpinner.setSelection(3);
							break;
						case 2:
							complexSpinner.setSelection(4);
							break;
						case 3:
							complexSpinner.setSelection(5);
							break;
						case 5:
							complexSpinner.setSelection(6);
							break;
						case 8:
							complexSpinner.setSelection(3);
							break;
						case 13:
							complexSpinner.setSelection(4);
							break;
						case 20:
							complexSpinner.setSelection(5);
							break;
						case 40:
							complexSpinner.setSelection(6);
							break;
						case 100:
							complexSpinner.setSelection(6);
							break;
						default:
							complexSpinner.setSelection(0);
							break;
					}
					
					double lat = selectedTask.getLatitude();
					double lon = selectedTask.getLongitude();
					output = String.valueOf(lon) + ", " + String.valueOf(lat);
					locationTextView.setText(output);
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
            
            //save button
            Button button = (Button) findViewById(R.id.button1);
            
    		button.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
    				try {
						save();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    			}
     
    		});
    		
    		// Delete a task
    		Button deleteButton = (Button) findViewById(R.id.btnDelete);
    		deleteButton.setOnClickListener(new OnClickListener() {
    			public void onClick(View arg0) {
    				try {
    					deleteTask();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    		
    		//Update location button
    		Button locButton = (Button) findViewById(R.id.locButton);
            
    		locButton.setOnClickListener(new OnClickListener() {
     
    			@Override
    			public void onClick(View arg0) {
    				TextView locationTextView = (TextView) findViewById(R.id.txtViewLocationData);
    				locationTextView.setText(output);
    			}
     
    		});
    		
    		Button mapButton = (Button) findViewById(R.id.mapButton);
    		mapButton.setOnClickListener(new OnClickListener() {
    			
				
				@Override
				public void onClick(View arg0) {
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://maps.google.com/maps?q="+lat+","+lon));
					startActivity(browserIntent);
					
				}
			});
    }
	class saveTasks implements Runnable {

		@Override
		public void run() {
			 // create and populate a task object.
	        Task task = null;
	        
	        Intent intent = getIntent();
	        String id = intent.getStringExtra(TASK_ID);
	        
	        if (id != null) {
	        	try {
					task = taskService.getTaskById(id);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        else
	        {
	        	task = new Task();
	        }
	        
	        Spinner complexSpinner = (Spinner) findViewById(R.id.complexSpinner);
	        String complexSelection = complexSpinner.getSelectedItem().toString();
	        if(complexSpinner.getSelectedItemPosition() != 0)
	        {
	        	task.setComplexity(Integer.parseInt(complexSelection));
	        }
	        else
	        {
	        	task.setComplexity(-1);
	        }
	        
	        DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker1);
	        int day = datePicker.getDayOfMonth();
	        int month = datePicker.getMonth();
	        int year =  datePicker.getYear();
	        Calendar calendar = Calendar.getInstance();
	        calendar.set(year, month, day);
	        task.setDueDate(calendar);
	        
	        Spinner repeatSpinner = (Spinner) findViewById(R.id.spinner1);
	        int repeatSelection = repeatSpinner.getSelectedItemPosition();
	        TaskRepeat repeat;
	        switch (repeatSelection){
				case 0:
					repeat = TaskRepeat.NONE;
					break;
				case 1:
					repeat = TaskRepeat.DAILY;
					break;
				case 2:
					repeat = TaskRepeat.WEEKLY;
					break;
				case 3:
					repeat = TaskRepeat.WEEKDAYS;
					break;
				case 4:
					repeat = TaskRepeat.WEEKENDS;
					break;
				case 5:
					repeat = TaskRepeat.MONTHY;
					break;
				case 6:
					repeat = TaskRepeat.YEARLY;
					break;
				default:
					repeat = TaskRepeat.NONE;
					break;
			}
	        task.setRepeat(repeat);
	        
	        Spinner statusSpinner = (Spinner) findViewById(R.id.Spinner01);
	        int statusSelection = statusSpinner.getSelectedItemPosition();
	        TaskStatus status;
	        switch (statusSelection){
				case 0:
					status = TaskStatus.INPROGRESS;
					break;
				case 1:
					status = TaskStatus.OVERDUE;
					break;
				case 2:
					status = TaskStatus.COMPLETE;
					break;
				default:
					status = TaskStatus.INPROGRESS;
					break;
			}
	        task.setStatus(status);
	        
	        EditText taskText = (EditText)findViewById(R.id.editText1);
	        task.setText(taskText.getText().toString());
	        
	        Location location = new Location(LocationManager.NETWORK_PROVIDER);
	        
	        TextView locationTextView = (TextView) findViewById(R.id.txtViewLocationData);
	        
	        String locString = (String) locationTextView.getText();
	        
	        String[] split = locString.split(", ");
	        
	        lon = Double.parseDouble(split[0].toString());
	        lat = Double.parseDouble(split[1].toString());
	        
	        location.setLongitude(lon);
	        location.setLatitude(lat);
	        
	        task.setLocation(location);
	        
	        try {
				taskService.saveTask(task);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	protected void deleteTask() throws Exception {
		
		// delete the task
		Intent intent = getIntent();
		String id = intent.getStringExtra(TASK_ID);
		TaskService taskService = new TaskService(this);
		Task task = taskService.getTaskById(id);
		taskService.deleteTask(task);
		 // call an activity that will search and show results.
        Intent plantResultsIntent = new Intent(this, ToDoList.class);

        startActivity(plantResultsIntent);
		
	}

	/**
	 * Saves Task object.
	 * @throws Exception
	 */
	private void save() throws Exception {

		//Threads the save process
		saveTasks st = new saveTasks();
		Thread stThread = new Thread(st);
		stThread.start();
		
        // call an activity that will search and show results.
        Intent plantResultsIntent = new Intent(this, ToDoList.class);

        startActivity(plantResultsIntent);
        
	}
}
